// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event)
  switch (event.action) {
    //获取排名
    case 'getRanking': {
      return getRanking(event)
    }
    //增加打卡次数
    case 'userInc': {
      return userInc(event)
    }
    //获取打卡次数
    case 'getUserInc': {
      return getUserInc(event)
    }
    //获取打卡分享数据
    case 'getUserSignData': {
      return getUserSignData(event)
    }
    //like
    case 'like': {
      return like(event)
    }
    //sendSubscribeMessageLike
    case 'sendSubscribeMessageLike': {
      return sendSubscribeMessageLike(event)
    }
    //sendSubscribeMessageLike
    case 'upDateUser': {
      return upDateUser(event)
    }
    case 'shenhe': {
      return shenhe(event)
    }
    case 'getWXACode': {
      return getWXACode(event)
    }
    default: {
      return
    }
  }
}

async function getRanking(event) {
  const count = await db.collection("sign")
    .where({
      signTime: _.gte(new Date(new Date(new Date().toLocaleDateString()).getTime())).and(_.lte(new Date(new Date(new Date()
        .toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)))
    })
    .count()
  return count
}

async function userInc(event) {
  const count = await db.collection("user")
    .where({
      _openid: event.useropenid
    })
    .update({
      data: {
        userInc: _.inc(1)
      }
    })

  return count
}


async function getUserInc(event) {
  const count = await db.collection("user")
    .where({
      _openid: event.useropenid
    })
    .get()

  return count
}

async function shenhe(event) {
  const count = await db.collection("sign")
    .where({
      _id: event._id
    })
    .update({
      data: {
        shenhe: true
      }
    })

  return count
}

async function getUserSignData(event) {
  const count = await db.collection("sign")
    .where({
      _id: event.id
    })
    .get()

  return count
}

async function like(event) {
  const count = await db.collection("sign")
    .where({
      _id: event.id
    })
    .update({
      data: {
        likeList: _.push(event.likeUserData),
        likeOpenid: _.push(event.likeUserOpenid)
      }
    })
  const sendResult = await db.collection("sign")
    .where({
      _id: event.id
    })
    .get()

  return {
    count,
    sendResult
  }
}


async function sendSubscribeMessageLike(event) {

  const {
    _openid
  } = event

  const sendResult = await cloud.openapi.subscribeMessage.send({
    touser: _openid,
    templateId: 'KTBWJIS4PKCwTDikQRDqLv_YmGnSAtKaFZCCWrjT3dE',
    page: `pages/index/share?toadySignId=${event._id}`,
    // 此处字段应修改为所申请模板所要求的字段
    data: {
      phrase1: {
        value: '审核已通过',
      },
      time2: {
        value: event.date,
      },
      thing3: {
        value: '无',
      }
    }
  })

  return sendResult
}

async function getWXACode(event) {
  // 此处将获取永久有效的小程序码，并将其保存在云文件存储中，最后返回云文件 ID 给前端使用

  const wxacodeResult = await cloud.openapi.wxacode.get({
    path: `pages/index/share?toadySignId=${event.id}`,
  })

  const fileExtensionMatches = wxacodeResult.contentType.match(/\/([^/]+)/)
  const fileExtension = (fileExtensionMatches && fileExtensionMatches[1]) || 'jpg'
  const cloudPathPost = event.openId + "/" + Date.parse(new Date());
  const uploadResult = await cloud.uploadFile({
    // 云文件路径，此处为演示采用一个固定名称
    cloudPath: `${cloudPathPost}.${fileExtension}`,
    // 要上传的文件内容可直接传入图片 Buffer
    fileContent: wxacodeResult.buffer,
  })

  if (!uploadResult.fileID) {
    throw new Error(`upload failed with empty fileID and storage server status code ${uploadResult.statusCode}`)
  }else{
    db.collection("sign")
    .where({
      _id: event.id
    })
    .update({
      data: {
        post:uploadResult.fileID
      }
    })
  }

  return uploadResult.fileID
}

async function upDateUser(event) {
  const count = await db.collection('user').where({
    _openid: event.userInfo.openId
  }).update({
    data: JSON.parse(event.data)
  })

  return count
}
